/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: FileTools.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Locale;

public class FileTools {

	static final String TAG = "FileTools";
	


	/**
	 * copy文件
	 * 
	 * @param is
	 *            输入�?
	 * @param os
	 *            输出�?
	 */
	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	/**
	 * 读取普�?路径文件
	 * 
	 * @param pathName
	 *            文件路径+名字
	 * @return
	 */
	public static InputStream readFile(String pathName) {
		File file = new File(pathName);
		FileInputStream fis = null;
		if (file.exists()) {
			try {
				fis = new FileInputStream(file);
			} catch (FileNotFoundException e) {
			}
		}
		return fis;
	}

	/**
	 * 读取普�?路径文件内容
	 * 
	 * @param pathName
	 *            文件路径
	 * @return
	 */
	public static String readFileString(String pathName) {
		File file = new File(pathName);
		FileInputStream fis = null;
		BufferedReader reader = null;
		String string = null;
		if (file.exists()) {
			try {
				fis = new FileInputStream(file);
				reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String s = reader.readLine(); s != null; s = reader.readLine()) {
					builder.append(s);
				}
				string = builder.toString();
			} catch (Exception e) {
			} finally {
				try {
					if(reader!=null){
						reader.close();
					}
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return string;
	}

	/**
	 * 读取assets文件夹下的txt字典库文�?
	 * 
	 * @param context
	 *            句柄
	 * @param fName
	 *            文件�?
	 * @return
	 */
	public static String readAssetsTXT(Context context, String fName) {
		try {
			AssetManager assetManager = context.getAssets();
			InputStream is = assetManager.open(fName);
			byte[] bytes = new byte[1024];
			int leng;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while ((leng = is.read(bytes)) != -1) {
				baos.write(bytes, 0, leng);
			}
			return new String(baos.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 写文�?
	 * 
	 * @param pathName
	 *            文件路径 + JSON内容
	 * @param content
	 */
	public static void writeFile(String pathName, String content) {
		File file = new File(pathName);
		if (file.exists()) {
			file.delete();
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			OutputStreamWriter osw = new OutputStreamWriter(fos);
			BufferedWriter bw = new BufferedWriter(osw);
			bw.write(content);
			bw.close();
		} catch (Exception e) {
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * 保存图片
	 * 
	 * @param path
	 * @param name
	 * @param bitmap
	 */
	public static void writeBitmap(String path, String name, Bitmap bitmap, int quality) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}

		File _file = new File(path + name);
		if (_file.exists()) {
			_file.delete();
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(_file);
			if (name != null && !"".equals(name)) {
				int index = name.lastIndexOf(".");
				if (index != -1 && (index + 1) < name.length()) {
					String extension = name.substring(index + 1).toLowerCase(Locale.getDefault());
					if ("png".equals(extension)) {
						// 修改图片质量�?5%
						bitmap.compress(Bitmap.CompressFormat.PNG, quality/* 100 */, fos);
					} else if ("jpg".equals(extension) || "jpeg".equals(extension)) {
						bitmap.compress(Bitmap.CompressFormat.JPEG, quality/* 100 */, fos);
					}
				}
			}
		} catch (FileNotFoundException e) {
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * 读取图片
	 * 
	 * @param pathName
	 * @return
	 */
	public static Bitmap readBitmap(String pathName) {
		InputStream in = FileTools.readFile(pathName);
		if (in != null) {
			Bitmap bitmap = BitmapFactory.decodeStream(in);
			try {
				in.close();
			} catch (IOException e) {
			}
			return bitmap;
		}
		return null;
	}

	/**
	 * 删除文件
	 * 
	 * @param file
	 */
	public static void deleteFile(File file) {
		if (file != null && file.isFile()) {
			file.delete();
		}
	}

	public static void deleteFile(String filename) {
		File f=new File(filename);
		if (f != null && f.isFile()) {
			f.delete();
		}
	}

	/**
	 * 判断SD是否存在
	 * 
	 * @return
	 */
	public static boolean isExternalStorage() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	/**
	 * 判断SD卡空间是否满
	 * 
	 * @return
	 */
	public static boolean storageIsFull() {
		StatFs fs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
		return !(fs.getAvailableBlocks() > 1);
	}

	/**
	 * 获得SD卡可用的存储空间大小
	 * 
	 * @return 可用的存储空�?
	 */
	public static long getAcailableSpave() {
		StatFs state = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
		long blockSize = state.getBlockSize();
//		long blockCount = state.getBlockCount();
		long availableCount = state.getAvailableBlocks();
//		long totalSpace = blockCount * blockSize / 1024; /* 存储空间大小 in KB */
		long freeSpace = availableCount * blockSize/* / 1024 */; /* 可用的存储空间大�? */
		return freeSpace;
	}

	/**
	 * 获取文件�?
	 * 
	 * @param filePathName
	 * @return
	 */
	public static String getFileName(String filePathName) {
		if (filePathName != null && !"".equals(filePathName)) {
			int index = filePathName.lastIndexOf('/');
			if (index != -1 && (index + 1) < filePathName.length()) {
				return filePathName.substring(index + 1);
			}
		}
		return "";
	}

	/**
	 * 递归删除目录
	 * 
	 * @param f
	 */
	public static void delFile(File f) {
		if (f.isDirectory()) {
			File[] list = f.listFiles();
			for (int i = 0; i < list.length; i++) {
				if (list[i].isDirectory()) {
					delFile(list[i]);
				} else {
					if (list[i].isFile()) {
						list[i].delete();
					}
				}
			}
			f.delete();
		} else {
			if (f.isFile())
				f.delete();
		}
	}

	/**
	 * 计算目录大小
	 * 
	 * @param f
	 * @return
	 */
	public static long calculateSpace(File f) {
		long length = 0;
		if (f != null && f.isDirectory()) {
			File[] list = f.listFiles();
			for (int i = 0; i < list.length; i++) {
				if (list[i].isFile()) {
					length += list[i].length();
				}
			}
		}

		return length;
	}

	/**
	 * 拷贝assets下的html到指定目�?
	 * 
	 * @param context
	 * @param toFile
	 * @param rewrite
	 */
	public static boolean copyAssetFile(Context context, File toFile, Boolean rewrite) {
		if (!toFile.getParentFile().exists()) {
			toFile.getParentFile().mkdirs();
		}
		if (toFile.exists() && rewrite) {
			toFile.delete();
		}
		InputStream fosfrom =null;
		OutputStream fosto=null;
		try {
			fosfrom = context.getAssets().open("ppg_help.html");
			fosto = new FileOutputStream(toFile);
			byte bt[] = new byte[1024];
			int c;
			while ((c = fosfrom.read(bt)) > 0) {
				fosto.write(bt, 0, c); // 将内容写到新文件当中
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			try {
				if(fosto!=null){
					fosto.close();
				}
				if(fosfrom!=null){
					fosfrom.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 读取html中的内容用于载入 data文件夹下无法直接载入html,�?��使用内容载入
	 * 
	 * @param strFilePath
	 *            html文件路径
	 * @return 内容字符�?
	 */
	public static String readTxtFile(String strFilePath) {
		String path = strFilePath;
		String content = ""; // 文件内容字符�?
		// 打开文件
		File file = new File(path);
		// 如果path是传递过来的参数，可以做�?��非目录的判断
		if (file.isDirectory()) {
		} else {
			InputStream instream = null;
			BufferedReader buffreader = null;
			try {
				instream = new FileInputStream(file);
				if (instream != null) {
					buffreader = new BufferedReader(new InputStreamReader(instream));
					String line;
					// 分行读取
					while ((line = buffreader.readLine()) != null) {
						content += line + "\n";
					}
				}
			} catch (FileNotFoundException e) {
			} catch (IOException e) {
			} finally {
				try {
					if (buffreader != null) {
						buffreader.close();
					}
					if (instream != null) {
						instream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return content;
	}

	/**
	 * 更新帮助html文件的内�?
	 * 
	 * @param content
	 *            �?��内容
	 * @param file
	 *            html 文件
	 * @param encoding
	 *            字符编码
	 * @throws IOException
	 */
	public static void updateHelpHtml(String content, File file, String encoding) throws IOException {
		BufferedWriter writer = null;
		if (file.exists()) {
			file.delete();
		}
		file.createNewFile();
		try {
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), encoding));
			writer.write(content);
		} finally {
			if (writer != null)
				writer.close();
		}
	}

	public static boolean checkAndMakeDir(String fileDir) {
		File file = new File(fileDir);
		if (!file.exists()) {
            return file.mkdirs();
		} else {
			return true;
		}
	}
	
	 /**
		 * 复制文件到目标文件夹
		 */
		public static boolean copy(String srcPath, String destPath) {
			FileInputStream fis=null;
			FileOutputStream fos=null;
			try {
				File file = new File(destPath);
				if (!file.exists()) {
					if (!file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					file.createNewFile();
				}

				fis = new FileInputStream(srcPath);
				fos = new FileOutputStream(destPath);

				int size = 0;
				byte[] buf = new byte[1024];
				while ((size = fis.read(buf)) != -1){
					fos.write(buf, 0, size);
				}
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}finally{
				try {
					if(fos!=null){
						fos.close();
					}
					if(fis!=null){
						fis.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}


	public static boolean fileIsExists(String filename){
		if(filename == null)
			return false;
		try{
			File f=new File(filename);
			if(!f.exists()){
				return false;
			}

		}catch (Exception e) {
			return false;
		}
		return true;
	}

	public static boolean fileIsExists(File filename){
		if(filename == null)
			return false;
		try{
			if(!filename.exists()){
				return false;
			}

		}catch (Exception e) {
			return false;
		}
		return true;
	}
}
